<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */

class Default_Model_Banner extends Zend_Db_Table{
	
	protected $_name    = "banners";
    protected $_primary = "id";
    
    public function saveData($data = array()){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            if(isset($data['id']) && $this->checkExists($data['id'])){
                $id = $data['id'];
                $db->update("banners", $data, "id = $id");
            }else{
                $db->insert('banners', $data);
            }
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('banner'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function getData($position, $count = 0){
        $db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        $select = $db->select()
                    ->from(array('t' => 'taxonomy'), array('id'))
                    ->join(array('b' => 'banners'), "b.position = t.id", array('name', 'image', 'link'))
                    ->where('t.name = ?', $position)
                    ->where('t.type = ?', 'banner')
                    ->where('b.status = 1')
                    ->order('b.id DESC');
        
        if($count == 1){
            $select->limit(1);
        }else if($count > 1){
            $select->limit($count);
        }
        
        $result = $db->fetchAll($select);
        
        return $result;
    }
    
    public function getAllData($position = null){
    	return $this->getData($position);
    }
    
    public function deleteData($id){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $db->delete('banners', "id = $id");
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('banner'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function checkExists($id){
        $option = array('table' => 'banners', 'field' => 'id');
    	$validator = new Zend_Validate_Db_RecordExists($option);
        
        if($validator->isValid($id)){
            return true;
        }
        
        return false;
    }
}